package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Log4j2
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }

        String originalFilename = multipartFile.getOriginalFilename();

        if (StringUtils.isBlank(originalFilename)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }

        String fileId = null;

        try {
            //上传图片
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
        }


        //从线程中获取wmUser
        WmUser wmuser = WmThreadLocalUtils.getUser();

        //需要插表  需要回显（返回图文信息对象）
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(wmuser.getId());  //此id 实体类中解释为 自媒体用户的id
        wmMaterial.setUrl(fileId);
        wmMaterial.setType((short) 0);  //0代表图片  1代表视频
        wmMaterial.setIsCollection((short) 0);  //0代表不收藏 1代表收藏
        wmMaterial.setCreatedTime(new Date());

        save(wmMaterial);

        //设置回显时的路径
        wmMaterial.setUrl(fileServerUrl + fileId);

        //返回前端整个图文对象
        return ResponseResult.okResult(wmMaterial);

    }





    /**
     * 修改素材收藏状态
     *
     * @param wmMaId
     * @param collectStatus
     * @return
     */
    @Override
    public ResponseResult editCollectStatus(Integer wmMaId, Short collectStatus) {
        //检查参数
        if (wmMaId == null || collectStatus == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 根据用户id 和素材id 去查询素材对象
        WmMaterial one = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, wmMaId).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        //如果没有 直接返回
        if (one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //如果有 重新设置收藏状态
        one.setIsCollection(collectStatus);
        //然后进行修改
        updateById(one);

        //TODO：上下两种方式都可以   只是下面这种 如果不是自己的图片的时候 不能删除 但是也显示  “操作成功”
//        update(Wrappers.<WmMaterial>lambdaUpdate()
//                .eq(WmMaterial::getId, wmMaId)
//                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                .set(WmMaterial::getIsCollection, collectStatus));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }




    /**
     * 删除素材
     *
     * @param wmMaId
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer wmMaId) {
        //检查参数
        if (wmMaId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断 文章和素材表的中间表 有没有该 素材的存在 如果有 那就是被引用了 不能删除
        WmNewsMaterial wmNewsMaterial = wmNewsMaterialMapper.selectOne(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, wmMaId));
        if (wmNewsMaterial != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前素材被引用，不能删除！");
        }

        //如果没有关联 根据图文id 和自媒体id 去查图文表 有没有这条数据
        WmMaterial one = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, wmMaId).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //如果有 删除fastDfs里面的图片 根据fileId去删 不需要访问的前缀
        String url = one.getUrl();
        //replace方法的意思是 替换  为了保险起见 如果url里有前缀的话 替换为""
        fastDFSClient.delFile(url.replace(fileServerUrl,""));

        //同时也删除图文信息表的数据
        removeById(wmMaId);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 查询素材
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto == null || dto.getIsCollection() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();
        Page page = new Page(dto.getPage(), dto.getSize());
        //只能查询自己的素材  条件对象上拼接eq 是否收藏 和eq自媒体id
        LambdaQueryWrapper<WmMaterial> lamQuery = new LambdaQueryWrapper<>();

        //如果查看收藏的  就拼接上收藏的条件  如果没有选查看收藏 就看全部的 就不拼接条件
        if (dto.getIsCollection()==1){
            lamQuery.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        lamQuery.eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());

        //根据图文创建时间倒序显示
        lamQuery.orderByDesc(WmMaterial::getCreatedTime);

        IPage pageList = page(page, lamQuery);
        PageResponseResult pageResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageList.getTotal());

        List<WmMaterial> wmMas = pageList.getRecords();

        ArrayList<WmMaterial> resultList = new ArrayList<>();

        for (WmMaterial wmMa : wmMas) {
            String url = wmMa.getUrl();
            wmMa.setUrl(fileServerUrl + url);
            resultList.add(wmMa);
        }

        pageResult.setData(resultList);
        return pageResult;
    }
}